package dao

import (
	"gorm.io/gorm"
	"micro-grpc-server/library/cache"
	"micro-grpc-server/library/database"
	"micro-grpc-server/services/music/internal/conf"
	"micro-grpc-server/services/music/internal/server"
	"micro-grpc-server/services/music/internal/server/migu"
	"sync"
)

type Dao struct {
	conf      *conf.Config
	Db        *gorm.DB
	serverMap map[string]server.Server
	m         sync.RWMutex
}

func NewDao(config *conf.Config) *Dao {
	return &Dao{
		conf:      config,
		Db:        database.NewMysql(config.Database),
		serverMap: map[string]server.Server{},
	}
}

// 获取对应场景的server
func (d *Dao) GetScenarioServer(scenario string) server.Server {
	d.m.RLock()
	srv, ok := d.serverMap[scenario]
	d.m.RUnlock()

	if ok == true {
		return srv
	}
	return d.cacheServer(scenario)
}

// 缓存server
func (d *Dao) cacheServer(scenario string) (srv server.Server) {
	switch scenario {
	case "migu":
		srv = migu.NewServer(cache.NewRedisCache(d.conf.Redis))
	}

	if srv != nil {
		d.m.Lock()
		d.serverMap[scenario] = srv
		d.m.Unlock()
	}

	return
}
